package top.mcwebsite.playandroid.home.ui

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.google.accompanist.pager.HorizontalPagerIndicator
import kotlinx.coroutines.launch
import top.mcwebsite.playandroid.common.uiWidget.skeleton
import top.mcwebsite.playandroid.home.model.BannerModel
import top.mcwebsite.playandroid.lib.mvi.model.Async
import java.util.Timer
import java.util.TimerTask

@Composable
internal fun Banner(
    asyncBanners: Async<List<BannerModel>>,
    onClickItem: (BannerModel) -> Unit,
) {
    val showSkeleton = remember(asyncBanners) {
        mutableStateOf(asyncBanners == Async.Loading)
    }
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(220.dp)
            .skeleton(showSkeleton.value)
    ) {
        when (asyncBanners) {
            is Async.Success<List<BannerModel>> -> {
                Banner(
                    bannerModels = asyncBanners.data,
                    onClickItem = onClickItem,
                )
            }
            is Async.Failed -> {
            }
            else -> {
            }
        }
    }
}

@Composable
fun Banner(
    bannerModels: List<BannerModel>,
    onClickItem: (BannerModel) -> Unit,
) {
    Banner(
        isLoop = true,
        data = bannerModels,
        onClickItem = onClickItem,
    ) {
        AsyncImage(
            model = it.imagePath,
            contentDescription = it.title,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxWidth()
                .clickable {
                    onClickItem(it)
                }
        )
    }
}

private const val VIRTUAL_COUNT = 1000000

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Banner(
    modifier: Modifier = Modifier,
    isLoop: Boolean = true,
    data: List<BannerModel>,
    onClickItem: (BannerModel) -> Unit,
    content: @Composable (BannerModel) -> Unit,
) {
    val initialPageIndex = if (data.isEmpty()) 0 else VIRTUAL_COUNT / 2
    val pagerState = rememberPagerState(
        initialPage = initialPageIndex
    ) {
        if (data.isEmpty()) 0 else VIRTUAL_COUNT
    }
    if (isLoop) {
        val coroutineScope = rememberCoroutineScope()
        DisposableEffect(Unit) {
            val timer = Timer()
            timer.schedule(object : TimerTask() {
                override fun run() {
                    coroutineScope.launch {
                        pagerState.animateScrollToPage(pagerState.currentPage + 1)
                    }
                }
            }, 3000, 3000)
            onDispose {
                timer.cancel()
            }
        }
    }
    val pageIndexMapping: (Int) -> Int = { i ->
        Math.floorMod(i - initialPageIndex, data.size)
    }
    Box(modifier = modifier) {
        HorizontalPager(
            state = pagerState,
            modifier = modifier,
        ) { i ->
            val index = pageIndexMapping(i)
            content(data[index])
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .align(Alignment.BottomStart)
                .background(
                    brush = Brush.verticalGradient(
                        listOf(
                            Color.Transparent,
                            Color.White
                        ),
                    )
                )
        )
        Column {
            Spacer(Modifier.weight(1f))
            Row(
                Modifier
                    .padding(horizontal = 16.dp, vertical = 5.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                val index = pageIndexMapping(pagerState.currentPage)
                Text(text = data[index].title)
                Spacer(modifier = Modifier.weight(1f))
                HorizontalPagerIndicator(
                    pagerState = pagerState,
                    pageCount = 3,
                    pageIndexMapping = pageIndexMapping
                )
            }
        }
    }
}